"""
Core Exceptions
核心异常定义
"""

from typing import Optional, Dict, Any


class MediaCreateException(Exception):
    """基础异常类"""
    
    def __init__(self, message: str, code: Optional[str] = None, details: Optional[Dict[str, Any]] = None):
        self.message = message
        self.code = code
        self.details = details or {}
        super().__init__(message)

    def to_dict(self) -> Dict[str, Any]:
        """转换为字典格式"""
        return {
            "error": self.code or self.__class__.__name__,
            "message": self.message,
            "details": self.details
        }


# 用户相关异常
class UserException(MediaCreateException):
    """用户相关异常基类"""
    pass


class UserNotFoundError(UserException):
    """用户不存在异常"""
    def __init__(self, message: str = "用户不存在", details: Optional[Dict[str, Any]] = None):
        super().__init__(message, "USER_NOT_FOUND", details)


class UserAlreadyExistsError(UserException):
    """用户已存在异常"""
    def __init__(self, message: str = "用户已存在", details: Optional[Dict[str, Any]] = None):
        super().__init__(message, "USER_ALREADY_EXISTS", details)


class InvalidCredentialsError(UserException):
    """凭据无效异常"""
    def __init__(self, message: str = "凭据无效", details: Optional[Dict[str, Any]] = None):
        super().__init__(message, "INVALID_CREDENTIALS", details)


class UserAccountLockedError(UserException):
    """用户账户被锁定异常"""
    def __init__(self, message: str = "账户已被锁定", details: Optional[Dict[str, Any]] = None):
        super().__init__(message, "ACCOUNT_LOCKED", details)


# 认证相关异常
class AuthenticationException(MediaCreateException):
    """认证相关异常基类"""
    pass


class AuthenticationError(AuthenticationException):
    """认证失败异常"""
    def __init__(self, message: str = "认证失败", details: Optional[Dict[str, Any]] = None):
        super().__init__(message, "AUTHENTICATION_FAILED", details)


class TokenExpiredError(AuthenticationException):
    """令牌过期异常"""
    def __init__(self, message: str = "令牌已过期", details: Optional[Dict[str, Any]] = None):
        super().__init__(message, "TOKEN_EXPIRED", details)


class TokenInvalidError(AuthenticationException):
    """令牌无效异常"""
    def __init__(self, message: str = "令牌无效", details: Optional[Dict[str, Any]] = None):
        super().__init__(message, "TOKEN_INVALID", details)


class PermissionDeniedError(AuthenticationException):
    """权限不足异常"""
    def __init__(self, message: str = "权限不足", details: Optional[Dict[str, Any]] = None):
        super().__init__(message, "PERMISSION_DENIED", details)


# 内容相关异常
class ContentException(MediaCreateException):
    """内容相关异常基类"""
    pass


class ContentNotFoundError(ContentException):
    """内容不存在异常"""
    def __init__(self, message: str = "内容不存在", details: Optional[Dict[str, Any]] = None):
        super().__init__(message, "CONTENT_NOT_FOUND", details)


class ContentGenerationError(ContentException):
    """内容生成失败异常"""
    def __init__(self, message: str = "内容生成失败", details: Optional[Dict[str, Any]] = None):
        super().__init__(message, "CONTENT_GENERATION_FAILED", details)


class ContentValidationError(ContentException):
    """内容验证失败异常"""
    def __init__(self, message: str = "内容验证失败", details: Optional[Dict[str, Any]] = None):
        super().__init__(message, "CONTENT_VALIDATION_FAILED", details)


class ContentStorageError(ContentException):
    """内容存储失败异常"""
    def __init__(self, message: str = "内容存储失败", details: Optional[Dict[str, Any]] = None):
        super().__init__(message, "CONTENT_STORAGE_FAILED", details)


# AI模型相关异常
class AIModelException(MediaCreateException):
    """AI模型相关异常基类"""
    pass


class AIModelNotAvailableError(AIModelException):
    """AI模型不可用异常"""
    def __init__(self, message: str = "AI模型不可用", details: Optional[Dict[str, Any]] = None):
        super().__init__(message, "AI_MODEL_NOT_AVAILABLE", details)


class AIModelRequestError(AIModelException):
    """AI模型请求失败异常"""
    def __init__(self, message: str = "AI模型请求失败", details: Optional[Dict[str, Any]] = None):
        super().__init__(message, "AI_MODEL_REQUEST_FAILED", details)


class AIModelRateLimitError(AIModelException):
    """AI模型速率限制异常"""
    def __init__(self, message: str = "AI模型请求过于频繁", details: Optional[Dict[str, Any]] = None):
        super().__init__(message, "AI_MODEL_RATE_LIMIT", details)


# 文件相关异常
class FileException(MediaCreateException):
    """文件相关异常基类"""
    pass


class FileNotFoundError(FileException):
    """文件不存在异常"""
    def __init__(self, message: str = "文件不存在", details: Optional[Dict[str, Any]] = None):
        super().__init__(message, "FILE_NOT_FOUND", details)


class FileUploadError(FileException):
    """文件上传失败异常"""
    def __init__(self, message: str = "文件上传失败", details: Optional[Dict[str, Any]] = None):
        super().__init__(message, "FILE_UPLOAD_FAILED", details)


class FileDownloadError(FileException):
    """文件下载失败异常"""
    def __init__(self, message: str = "文件下载失败", details: Optional[Dict[str, Any]] = None):
        super().__init__(message, "FILE_DOWNLOAD_FAILED", details)


class FileValidationError(FileException):
    """文件验证失败异常"""
    def __init__(self, message: str = "文件验证失败", details: Optional[Dict[str, Any]] = None):
        super().__init__(message, "FILE_VALIDATION_FAILED", details)


class FileSizeExceededError(FileException):
    """文件大小超出限制异常"""
    def __init__(self, message: str = "文件大小超出限制", details: Optional[Dict[str, Any]] = None):
        super().__init__(message, "FILE_SIZE_EXCEEDED", details)


# 任务队列相关异常
class TaskQueueException(MediaCreateException):
    """任务队列相关异常基类"""
    pass


class TaskNotFoundError(TaskQueueException):
    """任务不存在异常"""
    def __init__(self, message: str = "任务不存在", details: Optional[Dict[str, Any]] = None):
        super().__init__(message, "TASK_NOT_FOUND", details)


class TaskExecutionError(TaskQueueException):
    """任务执行失败异常"""
    def __init__(self, message: str = "任务执行失败", details: Optional[Dict[str, Any]] = None):
        super().__init__(message, "TASK_EXECUTION_FAILED", details)


class TaskTimeoutError(TaskQueueException):
    """任务超时异常"""
    def __init__(self, message: str = "任务执行超时", details: Optional[Dict[str, Any]] = None):
        super().__init__(message, "TASK_TIMEOUT", details)


# 数据库相关异常
class DatabaseException(MediaCreateException):
    """数据库相关异常基类"""
    pass


class DatabaseConnectionError(DatabaseException):
    """数据库连接失败异常"""
    def __init__(self, message: str = "数据库连接失败", details: Optional[Dict[str, Any]] = None):
        super().__init__(message, "DATABASE_CONNECTION_FAILED", details)


class DatabaseQueryError(DatabaseException):
    """数据库查询失败异常"""
    def __init__(self, message: str = "数据库查询失败", details: Optional[Dict[str, Any]] = None):
        super().__init__(message, "DATABASE_QUERY_FAILED", details)


# 系统相关异常
class SystemException(MediaCreateException):
    """系统相关异常基类"""
    pass


class ConfigurationError(SystemException):
    """配置错误异常"""
    def __init__(self, message: str = "配置错误", details: Optional[Dict[str, Any]] = None):
        super().__init__(message, "CONFIGURATION_ERROR", details)


class ServiceUnavailableError(SystemException):
    """服务不可用异常"""
    def __init__(self, message: str = "服务不可用", details: Optional[Dict[str, Any]] = None):
        super().__init__(message, "SERVICE_UNAVAILABLE", details)


class RateLimitExceededError(SystemException):
    """速率限制超出异常"""
    def __init__(self, message: str = "请求过于频繁，请稍后再试", details: Optional[Dict[str, Any]] = None):
        super().__init__(message, "RATE_LIMIT_EXCEEDED", details)


# 验证相关异常
class ValidationException(MediaCreateException):
    """验证相关异常基类"""
    pass


class ValidationError(ValidationException):
    """验证失败异常"""
    def __init__(self, message: str = "验证失败", details: Optional[Dict[str, Any]] = None):
        super().__init__(message, "VALIDATION_ERROR", details)


class InvalidInputError(ValidationException):
    """无效输入异常"""
    def __init__(self, message: str = "输入参数无效", details: Optional[Dict[str, Any]] = None):
        super().__init__(message, "INVALID_INPUT", details)


# 外部服务相关异常
class ExternalServiceException(MediaCreateException):
    """外部服务相关异常基类"""
    pass


class ExternalServiceConnectionError(ExternalServiceException):
    """外部服务连接失败异常"""
    def __init__(self, message: str = "外部服务连接失败", details: Optional[Dict[str, Any]] = None):
        super().__init__(message, "EXTERNAL_SERVICE_CONNECTION_FAILED", details)


class ExternalServiceTimeoutError(ExternalServiceException):
    """外部服务超时异常"""
    def __init__(self, message: str = "外部服务请求超时", details: Optional[Dict[str, Any]] = None):
        super().__init__(message, "EXTERNAL_SERVICE_TIMEOUT", details)


# 文件夹相关异常
class FolderException(MediaCreateException):
    """文件夹相关异常基类"""
    pass


class FolderNotFoundError(FolderException):
    """文件夹不存在异常"""
    def __init__(self, message: str = "文件夹不存在", details: Optional[Dict[str, Any]] = None):
        super().__init__(message, "FOLDER_NOT_FOUND", details)


class FolderAccessDeniedError(FolderException):
    """文件夹访问被拒绝异常"""
    def __init__(self, message: str = "无权访问此文件夹", details: Optional[Dict[str, Any]] = None):
        super().__init__(message, "FOLDER_ACCESS_DENIED", details)


class FolderNameConflictError(FolderException):
    """文件夹名称冲突异常"""
    def __init__(self, message: str = "文件夹名称已存在", details: Optional[Dict[str, Any]] = None):
        super().__init__(message, "FOLDER_NAME_CONFLICT", details)


# 标签相关异常
class TagException(MediaCreateException):
    """标签相关异常基类"""
    pass


class TagNotFoundError(TagException):
    """标签不存在异常"""
    def __init__(self, message: str = "标签不存在", details: Optional[Dict[str, Any]] = None):
        super().__init__(message, "TAG_NOT_FOUND", details)


class TagAlreadyExistsError(TagException):
    """标签已存在异常"""
    def __init__(self, message: str = "标签已存在", details: Optional[Dict[str, Any]] = None):
        super().__init__(message, "TAG_ALREADY_EXISTS", details)


# HTTP状态码映射
HTTP_STATUS_CODES = {
    "USER_NOT_FOUND": 404,
    "USER_ALREADY_EXISTS": 409,
    "INVALID_CREDENTIALS": 401,
    "ACCOUNT_LOCKED": 403,
    "AUTHENTICATION_FAILED": 401,
    "TOKEN_EXPIRED": 401,
    "TOKEN_INVALID": 401,
    "PERMISSION_DENIED": 403,
    "CONTENT_NOT_FOUND": 404,
    "CONTENT_GENERATION_FAILED": 500,
    "CONTENT_VALIDATION_FAILED": 400,
    "CONTENT_STORAGE_FAILED": 500,
    "AI_MODEL_NOT_AVAILABLE": 503,
    "AI_MODEL_REQUEST_FAILED": 500,
    "AI_MODEL_RATE_LIMIT": 429,
    "FILE_NOT_FOUND": 404,
    "FILE_UPLOAD_FAILED": 500,
    "FILE_DOWNLOAD_FAILED": 500,
    "FILE_VALIDATION_FAILED": 400,
    "FILE_SIZE_EXCEEDED": 413,
    "TASK_NOT_FOUND": 404,
    "TASK_EXECUTION_FAILED": 500,
    "TASK_TIMEOUT": 504,
    "DATABASE_CONNECTION_FAILED": 503,
    "DATABASE_QUERY_FAILED": 500,
    "CONFIGURATION_ERROR": 500,
    "SERVICE_UNAVAILABLE": 503,
    "RATE_LIMIT_EXCEEDED": 429,
    "VALIDATION_ERROR": 400,
    "INVALID_INPUT": 400,
    "EXTERNAL_SERVICE_CONNECTION_FAILED": 503,
    "EXTERNAL_SERVICE_TIMEOUT": 504,
    "FOLDER_NOT_FOUND": 404,
    "FOLDER_ACCESS_DENIED": 403,
    "FOLDER_NAME_CONFLICT": 409,
    "TAG_NOT_FOUND": 404,
    "TAG_ALREADY_EXISTS": 409,
}


def get_http_status_code(error_code: str) -> int:
    """获取HTTP状态码"""
    return HTTP_STATUS_CODES.get(error_code, 500)


def is_client_error(error_code: str) -> bool:
    """判断是否为客户端错误（4xx）"""
    status_code = get_http_status_code(error_code)
    return 400 <= status_code < 500


def is_server_error(error_code: str) -> bool:
    """判断是否为服务器错误（5xx）"""
    status_code = get_http_status_code(error_code)
    return status_code >= 500